package org.ycx.upms.web.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.common.validator.NotNullValidator;
import org.ycx.common.validator.ValidationErrorToString;
import org.ycx.upms.common.constants.SecurityConstants;
import org.ycx.upms.dao.model.*;
import org.ycx.upms.service.ISecPermissionService;
import org.ycx.upms.service.ISecRoleService;
import org.ycx.upms.service.ISecUserService;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SecRolecontroller
 * Created by yang on 2017-07-19 16:25:40.
 */
@Controller
@RequestMapping("/sec/role")
public class SecRoleController {

    private static Logger _log = LoggerFactory.getLogger (SecRoleController.class);

    private static final String PRE = "sec/role/";

    @Autowired
    private ISecRoleService service;

    @Autowired
    private ISecUserService userService;

    @Autowired
    private ISecPermissionService permissionService;

    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap) {
        return PRE + "index";
    }

    /**
     * 新增页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap) {
        return PRE + "create";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        SecRole bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "update";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/detail/{id}.html")
    public String detailPage(@PathVariable("id") int id, ModelMap modelMap) {
        SecRole bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "detail";
    }

    /**
     * 新增功能
     *
     * @param bean
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RespMSG create(SecRole bean, HttpSession session) {
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getRoleName (), new NotNullValidator ("角色名称"))
                .on (bean.getRoleDesc (), new NotNullValidator ("角色描述"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
            return error;
        }
        bean.setCreateTs (new Date ());
        bean.setUpdateTs (new Date ());
        bean.setCreateUid ((Integer) session.getAttribute (SecurityConstants.CURRENT_UID));
        bean.setUpdateUid ((Integer) session.getAttribute (SecurityConstants.CURRENT_UID));
        int count = service.insertSelective (bean);
        return new RespMSG (RespCode.SUCCESS);
    }

    /**
     * 更新功能
     *
     * @param id
     * @param bean
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, SecRole bean, HttpSession session) {
        //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getRoleName (), new NotNullValidator ("角色名称"))
                .on (bean.getRoleDesc (), new NotNullValidator ("角色描述"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
            return error;
        }
        if (id < 5) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc ("内置数据无法操作");
            return error;
        }
        bean.setUpdateTs (new Date ());
        bean.setUpdateUid ((Integer) session.getAttribute (SecurityConstants.CURRENT_UID));
        int count = service.updateByPrimaryKeySelective (bean);
        return new RespMSG (RespCode.SUCCESS);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public RespMSG delete(@PathVariable("ids") String ids) {
        if (ids.contains ("-1-") || ids.endsWith ("-1") || ids.startsWith ("1-") || ids.equals ("1")) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc ("内置数据无法操作");
            return error;
        } else {
            int count = service.deleteByPrimaryKeys (ids);
            if (count > 0) {
                return new RespMSG (RespCode.SUCCESS);
            } else {
                return new RespMSG (RespCode.FAIL);
            }
        }
    }


    @RequestMapping("/list")
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        SecRoleExample beanExample = new SecRoleExample ();
        if (!StringUtils.isBlank (sort) && !StringUtils.isBlank (order)) {
            beanExample.setOrderByClause (sort + " " + order);
        }
        //TODO 模糊查询定义
        List<SecRole> rows = service.selectByExampleForOffsetPage (beanExample, offset, limit);
        long total = service.countByExample (beanExample);
        Map<String, Object> result = new HashMap<> ();
        result.put ("rows", rows);
        result.put ("total", total);
        return result;
    }

    @RequestMapping("/permission")
    @ResponseBody
    public List<SecPermission> grantList() {
        SecPermissionExample ex = new SecPermissionExample ();
        ex.createCriteria ().andStateEqualTo ("0");
        return this.permissionService.selectByExample (ex);
    }

    @RequestMapping("/hasPermission")
    @ResponseBody
    public RespMSG hasPermission(Integer id) {
        RespMSG respMSG = new RespMSG (RespCode.SUCCESS);
        List<Integer> res = this.service.selectByRoleId (id);
        respMSG.setData (res);
        return respMSG;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/grant", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG grant(Integer rid, String ids) {
        this.service.updateGrant (rid, ids);
        RespMSG respMSG = new RespMSG (RespCode.SUCCESS);
        return respMSG;
    }

    @Autowired
    private StringRedisTemplate template;

    @RequestMapping(value = "/initRole", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG initRoles() {
        template.opsForValue ().set (SecurityConstants.SECURITY_LOAD_FLAG, "0");
        RespMSG respMSG = new RespMSG (RespCode.SUCCESS);
        return respMSG;
    }


    @RequestMapping("/user")
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = true, value = "rid") Integer rid) {
        //TODO 模糊查询定义
        List<SecUser> rows = userService.selectUserByRoleId (rid, offset, limit);
        long total = userService.countUserByRoleId (rid);
        Map<String, Object> result = new HashMap<> ();
        result.put ("rows", rows);
        result.put ("total", total);
        return result;
    }
}
